package com.demo.node;

import com.demo.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Madeline
 * @CreateTime: 2025-06-07
 * @Description: 全节点
 * @Version: 1.0
 */
public class FullNode extends AbstractNode {
    private JFrame mainFrame;
    private MineDialog mineDialog;
    private TxDialog txDialog;
    private WalletDialog walletDialog;
    private ArrayList<Boolean> isSpent;
    private Map<String, String> userInfo;

    public FullNode(String nodeId, int p2pPort, Map<String, String> userInfo) {
        super(nodeId, NodeType.FULL_NODE, p2pPort);
        this.userInfo = userInfo;
        this.isSpent = new ArrayList<>();
        // 初始化P2P网络
        p2pNetwork = new P2PNetwork(p2pPort, blockchain, NodeType.FULL_NODE,userInfo.get("publicKey"));
        createUI();
    }

    private void createUI() {
        mainFrame = new JFrame("全节点 - " + nodeId);
        mainFrame.setSize(500, 500);
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setLayout(new GridLayout(1, 2, 10, 0));

        // 左侧面板
        JPanel leftPanel = new JPanel(new GridLayout(3, 1, 10, 10));

        // 挖矿按钮
        JButton mineButton = new JButton("挖矿");
        userInfo.put("difficulty", String.valueOf(blockchain.getDifficulty()));
        mineDialog = new MineDialog(userInfo, blockchain, p2pNetwork);
        mineButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                SwingUtilities.invokeLater(() -> {
                    mineDialog.setVisible(true);
                });
            }
        });

        // 交易按钮
        JButton transactionButton = new JButton("交易");
        txDialog = new TxDialog(userInfo, blockchain, isSpent, p2pNetwork);
        transactionButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                SwingUtilities.invokeLater(() -> {
                    txDialog.getList();
                    txDialog.setVisible(true);
                });
            }
        });

        // 钱包按钮
        JButton walletButton = new JButton("钱包");
        walletButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                SwingUtilities.invokeLater(() -> {
                    walletDialog = new WalletDialog(userInfo, blockchain, isSpent);
                    walletDialog.setVisible(true);
                });
            }
        });

        leftPanel.add(mineButton);
        leftPanel.add(transactionButton);
        leftPanel.add(walletButton);

        // 右侧面板
        JPanel rightPanel = new JPanel();
        rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));

        // 创建用户头像
        ImageIcon originalIcon = new ImageIcon("D:\\BTC_BlockChain_Overwrite\\MyBlockChain_for_BTC\\res\\defaultImg.jpg");
        int rightPanelWidth = mainFrame.getWidth() / 2;
        int rightPanelHeight = mainFrame.getHeight() / 2;
        Image originalImage = originalIcon.getImage();
        Image scaledImage = originalImage.getScaledInstance(rightPanelWidth, rightPanelHeight, Image.SCALE_SMOOTH);
        ImageIcon scaledIcon = new ImageIcon(scaledImage);

        JLabel avatarLabel = new JLabel(scaledIcon);
        avatarLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

        // 用户信息标签
        JLabel userIdLabel = new JLabel("userId: " + userInfo.get("userId"));
        userIdLabel.setFont(new Font("Arial", Font.PLAIN, 20));
        userIdLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

        JLabel publicKeyLabel = new JLabel("pubKey: " + userInfo.get("publicKey"));
        publicKeyLabel.setFont(new Font("Arial", Font.PLAIN, 20));
        publicKeyLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

        JLabel privateKeyLabel = new JLabel("priKey: ****");
        privateKeyLabel.setFont(new Font("Arial", Font.PLAIN, 20));
        privateKeyLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

        // 点击显示私钥
        privateKeyLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                privateKeyLabel.setText("priKey: " + userInfo.get("privateKey"));
            }
        });

        rightPanel.add(avatarLabel);
        rightPanel.add(userIdLabel);
        rightPanel.add(publicKeyLabel);
        rightPanel.add(privateKeyLabel);

        // 添加节点状态信息
        // JLabel nodeStatusLabel = new JLabel("节点状态: 等待连接");
        // nodeStatusLabel.setFont(new Font("Arial", Font.PLAIN, 20));
        // nodeStatusLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        // rightPanel.add(nodeStatusLabel);
//
        // JLabel nodeTypeLabel = new JLabel("节点类型: 全节点");
        // nodeTypeLabel.setFont(new Font("Arial", Font.PLAIN, 20));
        // nodeTypeLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        // rightPanel.add(nodeTypeLabel);
//
        // JLabel chainInfoLabel = new JLabel("区块链高度: " + blockchain.getChain().size());
        // chainInfoLabel.setFont(new Font("Arial", Font.PLAIN, 20));
        // chainInfoLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        // rightPanel.add(chainInfoLabel);

        // 添加连接按钮
        JButton connectButton = new JButton("连接到全节点");
        connectButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        connectButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String ip = JOptionPane.showInputDialog("请输入全节点的IP地址：");
                String portStr = JOptionPane.showInputDialog("请输入全节点的端口：");
                if (ip != null && portStr != null) {
                    try {
                        int elderPort = Integer.parseInt(portStr);
                        p2pNetwork.connectToPeer(ip, elderPort);
                        JOptionPane.showMessageDialog(null, "连接请求已发送！");
                    } catch (NumberFormatException ex) {
                        JOptionPane.showMessageDialog(null, "无效的端口号！");
                    }
                }
            }
        });
        rightPanel.add(connectButton);

        mainFrame.add(leftPanel);
        mainFrame.add(rightPanel);
    }

    @Override
    public void start() {
    // 显示UI
        SwingUtilities.invokeLater(() -> {
            mainFrame.setVisible(true);
        });
    }

    public static void main(String[] args) {
        // 设置默认端口
        int port = 5889;
        String nodeId = "full_node";

        // 创建用户信息
        Map<String, String> userInfo = new HashMap<>();
        userInfo.put("userId", nodeId);
        userInfo.put("publicKey", "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEk+t+uYG05G/HXWDetcGwKSOq2xsx82S7/mDcrN66WKujhsz7S5gR7bH3aExfHuhki8ARNjk3xyZ6zhazQCa/zg==");
        userInfo.put("privateKey", "MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCA5Sjuwq2h1Lzk+yy1vcbMrbSAoIiGqCjQK6XGrWxPlIg==");

        // 创建并启动全节点
        FullNode fullNode = new FullNode(nodeId, port, userInfo);
        fullNode.start();
    }
}